package com.dog.basics.netty.kit;


import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.dog.basics.netty.util.NettyAttrUtil;
import com.dog.basics.netty.util.SessionSocketHolder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.socket.nio.NioSocketChannel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 最大的限制检查是否有心跳超时的客户端
 */
@Service
public class ServerHeartBeatHandlerImpl implements HeartBeatHandler {

    private final static Logger LOGGER = LoggerFactory.getLogger(ServerHeartBeatHandlerImpl.class);

    @Autowired
    private RouteHandler routeHandler;

    @Override
    public void process(ChannelHandlerContext ctx) throws Exception {
        
        long heartBeatTime = 30 * 3;

        Long lastReadTime = NettyAttrUtil.getReaderTime(ctx.channel());
        long now = DateUtil.currentSeconds();
        if (lastReadTime != null && (now - lastReadTime) > heartBeatTime) {
            Long sessionChannelId = SessionSocketHolder.getSession(ctx.channel().id().asLongText());
            if (ObjectUtil.isNotNull(sessionChannelId)) {
                LOGGER.warn("客户端[{}]心跳超时[{}]ms，需要关闭连接!", sessionChannelId, now - lastReadTime);
                routeHandler.userOffLine(sessionChannelId, (NioSocketChannel) ctx.channel());
                ctx.channel().close();
            }
        }
    }
}
